package com.sunxueqi.project.system.service.impl;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.sunxueqi.common.constant.StatusConstants;
import com.sunxueqi.common.utils.KeyGenerate;
import com.sunxueqi.common.utils.SecurityUtils;
import com.sunxueqi.project.system.dao.LocalFileMapper;
import com.sunxueqi.project.system.service.IFileService;
import com.sunxueqi.project.system.vo.LocalFile;

import cn.hutool.core.io.FileUtil;

@Service
public class FileServiceImpl implements IFileService{

	@Value("${upload-file-path}")
	private String filePath;
	
	@Autowired
	private LocalFileMapper localFileMapper;
	
	@Override
	public int uploadFile(MultipartFile multipartFile) {
		String id = KeyGenerate.getKeyId();
		
		// 获取文件的实际名
		String realName = multipartFile.getOriginalFilename();
		// 获取文件后缀名
		String suffix = FileUtil.extName(realName);
		// 为防止文件名重复，保存时将文件名修改为id进行存储
		File file = new File(filePath + "/" + id + "." +suffix);
		
		// 获取文件实际名
		saveFile(multipartFile, file);
		
		LocalFile localFile = new LocalFile();
		localFile.setId(id);
		localFile.setRealName(realName);
		localFile.setPath(filePath);
		localFile.setSuffix(suffix);
		localFile.setSize(multipartFile.getSize());
		localFile.setDeleteStatus(StatusConstants.NORMAL);
		localFile.setCreateBy(SecurityUtils.getLoginUserId());
		localFile.setCreateTime(new Timestamp(System.currentTimeMillis()));
		return localFileMapper.insert(localFile);
	}
	
	// 将文件写入到磁盘中
	private void saveFile(MultipartFile multipartFile, File file) {
		try {
			multipartFile.transferTo(file);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<LocalFile> selectLocalFileList(LocalFile localFile) {
		localFile.setDeleteStatus(StatusConstants.NORMAL);
		return localFileMapper.selectList(localFile);
	}

	
}
